package com.ftg.learn.util;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 */
@Component
public class RedisUtils {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public String getValueByKey(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void setValueByKey(String key, String value, Long time, TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, value,time,TimeUnit.SECONDS);
    }

    public void setValueByKey(String key, String value){
        Random random = new Random();
        int randomNum = 300 + random.nextInt(200);
        stringRedisTemplate.opsForValue().set(key, value,randomNum,TimeUnit.SECONDS);
    }

    public void deleteByKey(String key){
        Set<String> keys =  stringRedisTemplate.keys(key);
        if(keys != null)
            stringRedisTemplate.delete(keys);
    }

    public Boolean existsByKey(String key){
        return stringRedisTemplate.hasKey(key);
    }

}
